package com.dragonfly.shutter.controllers;

import java.io.IOException;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.dragonfly.shutter.beans.Message;
import com.dragonfly.shutter.services.UploadService;

/**
 * 上传图片控制类
 * @author 黄挺
 *
 */
@Controller
public class UploadController {
	@Autowired
	UploadService uploadService;	//上传服务类
	private static final int cacheSize = 40960;	//缓冲大小
	private HttpSession session;	//上传图片前的session（swfupload在上传文件后新建了一个session,此session用来找回原来的sesision）
	
	/**
	 * upload.html get处理
	 * @param session session
	 * @param albumID 相册ID
	 * @return upload.html页面
	 */
	@RequestMapping(value="/upload.html", method = RequestMethod.GET)
	public ModelAndView onLoad( HttpSession session,
			@RequestParam(value="albumID",required=false) Integer albumID)
	{
		Message message = null;
		
		Integer userID = (Integer)session.getAttribute("userID");
		
		//未登录的用户
		if(userID == null ){
			message = new Message("您尚未登录，请先登录", "请登录", "login.html");
			return new ModelAndView("message", "message", message);
		}
		
		//未指定相册
		if( albumID == null ){
			return new ModelAndView("albumSelect");
		}
		
		session.setAttribute("albumID", albumID);
		
		//在丢失session前保存session
		if(session != null){
			this.setSession(session);
		}
		
		return new ModelAndView("upload");
	}

	/**
	 * upload.html post处理
	 * @param request request
	 * @param response response
	 * @param albumID 相册ID
	 * @return 跳转页面：若出错，则跳转到出错页面，若没有，则跳转到upload.html
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/upload.html", method = RequestMethod.POST)
	public ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response){
		HttpSession newSession = request.getSession();
		
		//复制session里面的属性
		Enumeration<String> attrNames=  session.getAttributeNames();
		
		while(attrNames.hasMoreElements()){
			String attrName = attrNames.nextElement();
			newSession.setAttribute(attrName, session.getAttribute(attrName));
		}
		
		Message message = null;
		Integer userID = (Integer)newSession.getAttribute("userID");
		Integer albumID = (Integer)newSession.getAttribute("albumID");
		
		//未指定相册
		if( albumID == null ){
			message = new Message("请先选择要上传的相册", "未指定的相册", "/albumSelectList.html");
			return new ModelAndView("message", "message", message);
		}
		
		else{
			DiskFileItemFactory factory = new DiskFileItemFactory();	 
			factory.setSizeThreshold(cacheSize); //设置缓冲区大小
			ServletFileUpload upload = new ServletFileUpload(factory);
        
			try {
				List<FileItem> items = upload.parseRequest(request);
				uploadService.doService(items, userID, albumID, request.getRequestURL().toString());
			} catch (FileUploadException e) {
				e.printStackTrace();
				message = new Message("上传出错啦～", "操作失败", "/Dragonfly/");
				return new ModelAndView("message", "message", message);
			} catch (IOException e) {
				e.printStackTrace();
				message = new Message("上传出错啦～", "操作失败", "/Dragonfly/");
				return new ModelAndView("message", "message", message);
			} catch (Exception e) {
				e.printStackTrace();
				message = new Message("上传出错啦～", "操作失败", "/Dragonfly/");
				return new ModelAndView("message", "message", message);
			}
			
			return new ModelAndView("redirect:/album.html?albumID="+albumID);
		}
	}
	
	/**
	 * 设置session
	 * @param session 要设置的session
	 */
	public void setSession(HttpSession session) {
		this.session = session;
	}

	/**
	 * 获取session
	 * @return session
	 */
	public HttpSession getSession() {
		return session;
	}
 }
